package io.github.jyrmc.gmcp.task

import io.github.jyrmc.gmcp.utils.GenerateMarkdownUtil
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.TaskAction

/**
 * 创建于 2020-01-08 16:37
 *
 * @author jiangyun
 * @类说明 任务类
 */
open class GenerateMarkdownTask : DefaultTask() {
    /**
     * 数据库类型
     */
    @Input
    lateinit var dbType: String

    /**
     * 数据库连接地址
     */
    @Input
    lateinit var url: String

    /**
     * 端口
     */
    @Input
    var port: Int = 3306

    /**
     * 数据库名称
     */
    @Input
    lateinit var database: String

    /**
     * 用户名
     */
    @Input
    lateinit var userName: String

    /**
     * 密码
     */
    @Input
    lateinit var password: String

    /**
     * 文件生成目录
     */
    @Input
    lateinit var projectPath: String

    @TaskAction
    fun generateAction() {
        if (dbType.isBlank()) {
            println("database type can't be null or empty")
            return
        }
        if (url.isBlank()) {
            println("url can't be null or empty")
            return
        }
        if (database.isBlank()) {
            println("databaseName can't be null or empty")
            return
        }
        if (userName.isBlank()) {
            println("userName can't be null or empty")
            return
        }
        if (password.isBlank()) {
            println("password can't be null or empty")
            return
        }
        if (projectPath.isBlank()) {
            println("genrate file path can't be null or empty")
            return
        }

        url = when (dbType) {
            "mysql" -> "jdbc:mysql://${url}:${port}/${database}?useUnicode=true&serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&autoReconnect=true&failOverReadOnly=false&tinyInt1isBit=false"
            "postgresql" -> "jdbc:postgresql://${url}:${port}/${database}"
            // "h2" -> "jdbc:h2:"
            else -> ""
        }

        try {
            println("========================== start export database ==========================")
            println("========================== author: iwiteks-jy    ==========================")

            GenerateMarkdownUtil.export(dbType, url, database, userName, password, projectPath)
        } catch (ex: Exception) {
            println(ex)
        } finally {
            println("========================== end generate code ==========================")
        }
    }
}